﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using JXT.PrimaryKey.Batman.Extensions;
using JXT.PrimaryKey.Batman.Core.Security;
using JXT.PrimaryKey.Batman.Core.Language;
using JXT.PrimaryKey.Batman.Core.Infrastructure;
using JXT.PrimaryKey.Batman.Web.Security;
using JXT.PrimaryKey.Batman.Web.Mvc.Models;
using JXT.PrimaryKey.Batman.Web.Mvc.Controllers;
using JXT.PrimaryKey.Batman.Web.Mvc.Results;

namespace JXT.PrimaryKey.Batman.Web.Mvc.Filters
{
    public class UserAuthorizationAttribute : AuthorizeAttribute
    {
        public string AuthorityName { get; private set; }

        public object ExpectedValue { get; private set; }

        public AuthorizationType Type { get; set; }

        public UserAuthorizationAttribute()
            : this("islogin", true)
        {
        }

        public UserAuthorizationAttribute(string authorityName, object expectedValue)
        {
            AuthorityName = authorityName;
            ExpectedValue = expectedValue;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //base.OnAuthorization(filterContext);
            var controller = filterContext.Controller as BaseController;
            IMembership membership = controller.Membership;
            if (!membership.IsLogin)
            {
                filterContext.Result = createErrorResult();
                return;
            }
            bool result = true;
            if (!AuthorityName.Equals("islogin", StringComparison.InvariantCultureIgnoreCase))
            {
                result = membership.Check(AuthorityName, ExpectedValue, Type);
            }
            result = result && membership.Check("IsLock", false, AuthorizationType.Equal);
            if (!result)
            {
                filterContext.Result = createErrorResult();
            }
        }

        private static ViewResult createErrorResult()
        {
            var messageResult = new MessageResult()
            {
                Message = new ViewMessage()
                {
                    Message = "SystemWeb_UserAuthorization_ErrorMessage",
                    Icon = MessageIcon.Error
                }
            };
            messageResult.Message.Urls.Add(new JumpUrl()
            {
                Text = "SystemWeb_CommonString_Login",
                Type = JumpType.Route,
                Value = new { controller = "user", action = "login" }
            });
            return messageResult;
        }
    }
}
